package com.itic.web.pay.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.utils.IpAddressHelper;
import com.itic.ht.mem.distribution.persistence.model.Cate;
import com.itic.ht.mem.distribution.service.CateService;
import com.itic.ht.mem.member.persistence.model.WebMember;
import com.itic.ht.mem.member.service.WebMemberService;
import com.itic.ht.mem.memberdetail.persistence.model.WebMemberDetail;
import com.itic.ht.mem.memberdetail.service.WebMemberDetailService;
import com.itic.ht.mem.mtype.persistence.model.WebmType;
import com.itic.ht.mem.mtype.service.WebmTypeService;
import com.itic.ht.mem.order.persistence.model.MemberOrder;
import com.itic.ht.mem.order.service.MemberOrderService;
import com.itic.ht.mem.orderdetail.persistence.model.MemberOrderDetail;
import com.itic.ht.mem.orderdetail.service.MemberOrderDetailService;
import com.itic.ht.mem.performance.persistence.model.Performance;
import com.itic.ht.mem.performance.persistence.model.Performancedetail;
import com.itic.ht.mem.performance.service.PerformanceService;
import com.itic.ht.mem.performance.service.PerformancedetailService;
import com.itic.web.mem.order.service.AppOrderService;
import com.itic.web.mem.order.vo.MemberOrderVo;
import com.itic.web.pay.common.PayCommon;
import com.itic.web.pay.config.PaymentUtil;
import com.itic.web.pay.config.WeixinpayConfig;
import com.itic.web.pay.config.XmlUtil1;
import com.itic.web.qo.TokenData;
import com.itic.web.ro.ResResult;

@Service
@Transactional
public class WeiXinService {
	@Autowired
	private WebMemberService webMemberService;
	@Autowired
	private MemberOrderService memOrderService;
	@Autowired
    private MemberOrderDetailService memOrderDetailService;
	@Autowired
	private WebMemberDetailService memDetailService;
	@Autowired
	private CateService cateService;
	@Autowired
	private PerformanceService performanceService;
	@Autowired
	private PerformancedetailService performancedetailService;
	@Resource
	private AppOrderService appOrderService;
	@Resource
	private WebmTypeService webmTypeService;
	public Map <String,Object> precreateOrderByWX(MemberOrder temp, TokenData data, String itemId, HttpServletRequest request) {
		Map <String,Object>resultMap =new HashMap<String,Object>();
		//如果金额为0，那么返回失败
		
		
		//生成订单
		ResResult order = appOrderService.getOrder(temp,data,itemId);
		//如果订单生成失败，那么返回失败
		if(!order.getCode().equals("200")){
			
		}
		SortedMap<Object, Object> map = new TreeMap<Object, Object>();
		String remortIP = IpAddressHelper.getRemortIP(request);
		map.put("appid",WeixinpayConfig.APP_ID); // appid
		map.put("mch_id", WeixinpayConfig.MCH_ID);// 商户号
		map.put("nonce_str", PaymentUtil.createNoce_str());// 随机字符串,不长于32位
		map.put("body",webmTypeService.get(itemId).getName());// 商品描述
		map.put("total_fee",String.valueOf(webmTypeService.get(itemId).getPrice().multiply(new BigDecimal("100").stripTrailingZeros())));//商品总金额String.valueOf((long)d)
		//MemberOrderVo vo 
		MemberOrderVo datas = (MemberOrderVo) order.getDatas();
		map.put("out_trade_no",datas.getOrderNum());/// 商户订单号
		map.put("spbill_create_ip", remortIP);/// ip
		map.put("notify_url", WeixinpayConfig.NOTIFY_URL);/// 通知地址
		map.put("trade_type", "APP");//// 交易类型
		map.put("sign", PaymentUtil.createSign("utf-8", map));// 签名

		String requestXML = PaymentUtil.getRequestXml(map);
		System.out.println("!!!!"+requestXML);
		String result = PaymentUtil.httpsRequest(WeixinpayConfig.GATEURL, "POST", requestXML);
		Map<Object, Object> bean = new HashMap<Object,Object>();
		bean = XmlUtil1.xmlToBean(result);
       System.out.println("*********"+bean.get("return_code"));
      if(bean.get("return_code").equals("SUCCESS")){
    	  //二次签名
    		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("appid", WeixinpayConfig.APP_ID);
			parameters.put("partnerid", WeixinpayConfig.MCH_ID);
			parameters.put("prepayid",bean.get("prepay_id"));
			parameters.put("package", "Sign=WXPay");
			parameters.put("noncestr", bean.get("nonce_str"));
			parameters.put("timestamp", System.currentTimeMillis()/1000);
			String secondSign=PaymentUtil.createSign("utf-8", parameters);
			parameters.put("sign", secondSign);
			resultMap.put("param", parameters);
			resultMap.put("flag", "0");
      }else{
    	  resultMap.put("flag", "1");
      }

	   return resultMap;
	}
	
	/**
	 * 回调后，处理逻辑
	 * @param bean
	 * @throws ParseException 
	 */
	public void completeOrder(Map<Object, Object> bean) throws ParseException {

		// 只处理支付成功的订单: 修改交易表状态,支付成功
		MemberOrder order = memOrderService.getMemberOrderByOrderNum(bean.get("out_trade_no").toString());
		order.setStatus("1"); // 支付完成
		memOrderService.edit(order); // 更新交易表中状态
		// 根据用户购买订单更新用户的会员状态
		// 根据订单查询用户
		WebMember webMember = webMemberService.getMemberByAccount(order.getAccount());
		// 获取用户购买的会员信息
		MemberOrderDetail orderDetail = memOrderDetailService
				.getMemOrderDetailByOrderNum(bean.get("out_trade_no").toString());
		WebmType webmType = webmTypeService.get(orderDetail.getItemId());
		WebMemberDetail memberDetail = memDetailService.getMemberDetailByAccount(webMember.getAccount());

		// 普通用户
		if (DBConst.MEMBER_GENERAL.equals(webMember.getCategory())) {
			// 更新用户会员详细信息
			memberDetail = PayCommon.getNewMemberDetail(webMember, webmType, memberDetail);
			memDetailService.edit(memberDetail);
			// 查询上级和上级的上级信息，
			// 增加上级用户业绩流水等信息
			Performancedetail memberWithdraw = this.addMemberWithdraw(memberDetail, webmType);
			WebMember newWebMember = PayCommon.getNewWebMember(webmType, webMember, memberWithdraw);
			// 直接更新用户会员状态
			webMemberService.edit(newWebMember);

		} else {
			// 会员用户
			// 判断会员用户的会员级别
			WebmType memType = webmTypeService.get(webMember.getCategory());
			// 查询购买级别
			// 购买级别比用户级别高
			if (webmType.getLevel() > memType.getLevel()) {
				// 更新用户会员状态
				memberDetail = PayCommon.getNewMemberDetail(webMember, webmType, memberDetail);
				memDetailService.edit(memberDetail);
				Performancedetail memberWithdraw = this.addMemberWithdraw(memberDetail, webmType);
				WebMember newWebMember = PayCommon.getNewWebMember(webmType, webMember, memberWithdraw);
				// 直接更新用户会员状态
				webMemberService.edit(newWebMember);
			} else if (webmType.getLevel().equals(memType.getLevel())) {
				// 级别相同时，判断用户当前会员级别的时间是否为-1（永久）不更新数据，保存订单记录
				memberDetail = PayCommon.getNewMemberDetail(webMember, webmType, memberDetail);
				// 更新用户会员详细信息
				memDetailService.edit(memberDetail);
				// 增加上级用户业绩流水等信息
				Performancedetail memberWithdraw = this.addMemberWithdraw(memberDetail, webmType);
				WebMember newWebMember = PayCommon.getNewWebMember(webmType, webMember, memberWithdraw);
				// 直接更新用户会员状态
				webMemberService.edit(newWebMember);
			} else {
				memberDetail = PayCommon.getNewMemberDetail(webMember, webmType, memberDetail);
				// 增加上级用户业绩流水等信息
				Performancedetail memberWithdraw = this.addMemberWithdraw(memberDetail, webmType);
				WebMember newWebMember = PayCommon.getNewWebMember(webmType, webMember, memberWithdraw);
				// 直接更新用户会员状态
				webMemberService.edit(newWebMember);
			}
		}
		
		
	}
	
	
	   
		private Performancedetail addMemberWithdraw(WebMemberDetail memberDetail,WebmType webmType){
			//查询分销费率
	     	List<Cate> list = cateService.list(null);
	     	Cate cate = list.get(0);
	     	//一级分销费率
	     	BigDecimal oneLevelCate = cate.getOneLevelCate();
	     	//二级分销费率
	     	BigDecimal twoLevelCate = cate.getTwoLevelCate();
	     	//三级分销费率 
	     	BigDecimal thirdLevelCate = cate.getThirdLevelCate();
	     	Performance performance = new Performance();
	     	Performancedetail performancedetail = new Performancedetail();
			if(null!=memberDetail&&memberDetail.getPid().length()==11){
	     		//判断上级用户是否存在
	     		WebMember member2 = webMemberService.getMemberByAccount(memberDetail.getPid());
	     		if(null!=member2){
	     			//上级用户存在时，查询该用户是否还有上级
	     			//增加最上级用户的业绩，余额，流水等信息
	 				performance = PayCommon.getNewPerformance(member2, webmType, oneLevelCate);
	 				performanceService.add(performance);
	 				//增加当前用户的收益流水
	 				performancedetail = PayCommon.getNewPerformancedetail(member2, webmType, oneLevelCate);
	 				performancedetailService.add(performancedetail);
	     			WebMemberDetail memberDetail2 = memDetailService.getMemberDetailByAccount(member2.getAccount());
	     			member2.setBalance(member2.getBalance().add(new BigDecimal(performancedetail.getIncome().toString())));
	 				webMemberService.edit(member2);
	     			WebMember member3 = webMemberService.getMemberByAccount(memberDetail2.getPid());
	     			performancedetail.setRevenueSources(memberDetail.getAccount());
	     			if(null!=member3){
	     				//上级用户存在时，查询该用户是否还有上级
	     				//增加最上级用户的业绩，余额，流水等信息
	     				performance = PayCommon.getNewPerformance(member3, webmType, twoLevelCate);
	     				performanceService.add(performance);
	     				//增加当前用户的收益流水
	     				performancedetail = PayCommon.getNewPerformancedetail(member3, webmType, twoLevelCate);
	     				performancedetailService.add(performancedetail);
	     				member3.setBalance(member3.getBalance().add(new BigDecimal(performancedetail.getIncome().toString())));
	     				webMemberService.edit(member3);
	         			WebMemberDetail memberDetail3 = memDetailService.getMemberDetailByAccount(member3.getAccount());
	         			WebMember member4 = webMemberService.getMemberByAccount(memberDetail3.getPid());
	         			//判断最上级是否存在
	         			if(null!=member4){
	         				//增加最上级用户的业绩，余额，流水等信息
	         				performance = PayCommon.getNewPerformance(member4, webmType, thirdLevelCate);
	         				performanceService.add(performance);
	         				//增加当前用户的收益流水
	         				performancedetail = PayCommon.getNewPerformancedetail(member4, webmType, thirdLevelCate);
	         				performancedetailService.add(performancedetail);
	         				member4.setBalance(member4.getBalance().add(new BigDecimal(performancedetail.getIncome().toString())));
	         				webMemberService.edit(member4);
	         			}
	     				
	     			}
	     		}
	     	}
			return performancedetail;
		}

	
}
